package com.css.zfzx.sjcj.modules.hddcRSInterpretationPolygon.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcRSInterpretationPolygon.repository.HddcRsinterpretationpolygonNativeRepository;
import com.css.zfzx.sjcj.modules.hddcRSInterpretationPolygon.repository.HddcRsinterpretationpolygonRepository;
import com.css.zfzx.sjcj.modules.hddcRSInterpretationPolygon.repository.entity.HddcRsinterpretationpolygonEntity;
import com.css.zfzx.sjcj.modules.hddcRSInterpretationPolygon.service.HddcRsinterpretationpolygonService;
import com.css.zfzx.sjcj.modules.hddcRSInterpretationPolygon.viewobjects.HddcRsinterpretationpolygonQueryParams;
import com.css.zfzx.sjcj.modules.hddcRSInterpretationPolygon.viewobjects.HddcRsinterpretationpolygonVO;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author zhangping
 * @date 2020-11-30
 */
@Service
public class HddcRsinterpretationpolygonServiceImpl implements HddcRsinterpretationpolygonService {

	@Autowired
    private HddcRsinterpretationpolygonRepository hddcRsinterpretationpolygonRepository;
    @Autowired
    private HddcRsinterpretationpolygonNativeRepository hddcRsinterpretationpolygonNativeRepository;

    @Override
    public JSONObject queryHddcRsinterpretationpolygons(HddcRsinterpretationpolygonQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcRsinterpretationpolygonEntity> hddcRsinterpretationpolygonPage = this.hddcRsinterpretationpolygonNativeRepository.queryHddcRsinterpretationpolygons(queryParams, curPage, pageSize, sort, order);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcRsinterpretationpolygonPage);
        return jsonObject;
    }


    @Override
    public HddcRsinterpretationpolygonEntity getHddcRsinterpretationpolygon(String id) {
        HddcRsinterpretationpolygonEntity hddcRsinterpretationpolygon = this.hddcRsinterpretationpolygonRepository.findById(id).orElse(null);
         return hddcRsinterpretationpolygon;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcRsinterpretationpolygonEntity saveHddcRsinterpretationpolygon(HddcRsinterpretationpolygonEntity hddcRsinterpretationpolygon) {
        String uuid = UUIDGenerator.getUUID();
        hddcRsinterpretationpolygon.setUuid(uuid);
        hddcRsinterpretationpolygon.setCreateUser(PlatformSessionUtils.getUserId());
        hddcRsinterpretationpolygon.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcRsinterpretationpolygon.setIsValid("1");
        this.hddcRsinterpretationpolygonRepository.save(hddcRsinterpretationpolygon);
        return hddcRsinterpretationpolygon;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcRsinterpretationpolygonEntity updateHddcRsinterpretationpolygon(HddcRsinterpretationpolygonEntity hddcRsinterpretationpolygon) {
        UpdateUtil.copyNullProperties(hddcRsinterpretationpolygonRepository.findByUuidAndIsValid(hddcRsinterpretationpolygon.getUuid(), "1"), hddcRsinterpretationpolygon);
        hddcRsinterpretationpolygon.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcRsinterpretationpolygon.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcRsinterpretationpolygonRepository.save(hddcRsinterpretationpolygon);
        return hddcRsinterpretationpolygon;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcRsinterpretationpolygons(List<String> ids) {
        List<HddcRsinterpretationpolygonEntity> hddcRsinterpretationpolygonList = this.hddcRsinterpretationpolygonRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcRsinterpretationpolygonList) && hddcRsinterpretationpolygonList.size() > 0) {
            for(HddcRsinterpretationpolygonEntity hddcRsinterpretationpolygon : hddcRsinterpretationpolygonList) {
                hddcRsinterpretationpolygon.setIsValid("0");
                hddcRsinterpretationpolygon.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcRsinterpretationpolygon.setUpdateTime(new Date());
                this.hddcRsinterpretationpolygonRepository.save(hddcRsinterpretationpolygon);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public void exportFile(HddcRsinterpretationpolygonQueryParams queryParams, HttpServletResponse response) {
        List<HddcRsinterpretationpolygonEntity> yhDisasterEntities = hddcRsinterpretationpolygonNativeRepository.exportYhDisasters(queryParams);
        List<HddcRsinterpretationpolygonVO> list=new ArrayList<>();
        for (HddcRsinterpretationpolygonEntity entity:yhDisasterEntities) {
            HddcRsinterpretationpolygonVO yhDisasterVO=new HddcRsinterpretationpolygonVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "航、卫片解译面-面", "航、卫片解译面-面", HddcRsinterpretationpolygonVO.class, "航、卫片解译面-面.xls", response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcRsinterpretationpolygonVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcRsinterpretationpolygonVO.class, params);
            List<HddcRsinterpretationpolygonVO> list = result.getList();
            // Excel条数据
            int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcRsinterpretationpolygonVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcRsinterpretationpolygonVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }
    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList( List<HddcRsinterpretationpolygonVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcRsinterpretationpolygonEntity yhDisasterEntity = new HddcRsinterpretationpolygonEntity();
            HddcRsinterpretationpolygonVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcRsinterpretationpolygon(yhDisasterEntity);
        }
    }

}
